package com.example.searchcenter.activity;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.searchcenter.R;
import com.example.searchcenter.helper.ImageLoader;
import com.example.searchcenter.helper.JSONParser;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat") public class DetailActivity extends Activity{

	TextView activity_id;
	TextView name;
	TextView location;
	TextView time;
	TextView date;
	TextView des;
	ImageView thumbnail;
	String id_activity;
	String name_activity;
	String beginDay;
	public ImageLoader imageLoader;

	public Log log;
	// getActionBar (Back)
	private ActionBar actionBar;
	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();

	// single product url
	private static final String url_detail_activity = "http://tinhnguyen.edu.vn/apis/getActivityDetail";
	private static final String url_image = "https://tinhnguyen.edu.vn/public/img/activities/thumbs/";
	static final String TAG_SUCCESS = "success";
	static final String TAG_ACTIVITIES = "activities";
	static final String TAG_ID_ACTIVITY = "cid";
	static final String TAG_CREATEDATE = "createDate";
	static final String TAG_NAME = "name";
	static final String TAG_DESCRIPTION = "description";
	static final String TAG_STARTDAY = "startday";
	static final String TAG_ENDDAY = "endday";
	static final String TAG_LOCATION = "vplaceName";
	static final String TAG_THUMBNAILIMAGEURL = "thumbnailImageUrl";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_activity);

		// check version sdk
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}

		// getting article details from intent
		Intent i = getIntent();

		// getting activity id (pid) from intent
		id_activity = i.getStringExtra(TAG_ID_ACTIVITY);

		// Getting complete article details in background thread
		new GetActivityDetails().execute();

		// getActionBar()
		actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setHomeButtonEnabled(true);

	}

	/**
	 * Background Async Task to Get complete article details
	 * */
	class GetActivityDetails extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DetailActivity.this);
			pDialog.setMessage("Loading article details. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Getting activity details in background thread
		 * */
		protected String doInBackground(String... params) {
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					// Check for success tag
					int success;

					try {
						// Building Parameters
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("id", id_activity));

						// getting product details by making HTTP request
						// Note that product details url will use GET request
						JSONObject json = jsonParser.makeHttpRequest(
								url_detail_activity, "GET", params);

						// check your log for json response
						Log.d("ACtivity Details", json.toString());

						// json success tag
						success = json.getInt(TAG_SUCCESS);

						// Toast.makeText(getApplicationContext(),params.toString(),
						// Toast.LENGTH_LONG).show();

						if (success == 1) {
							imageLoader = new ImageLoader(
									getApplicationContext());
							// successfully received activity details
							JSONArray activityObj = json
									.getJSONArray(TAG_ACTIVITIES); // JSON Array

							// get first article object from JSON Array
							JSONObject activity = activityObj.getJSONObject(0);

							// Toast.makeText(getApplicationContext(),product.toString(),
							// Toast.LENGTH_LONG).show();
							// activity with this pid found
							// Edit Text

							// activity_id = (TextView)
							// findViewById(R.id.id_activity_detail);
							
							name = (TextView) findViewById(R.id.name_activity_detail);
							location = (TextView) findViewById(R.id.location_activity_detail);
							time = (TextView) findViewById(R.id.time_activity_detail);
							date = (TextView) findViewById(R.id.createDateActvity);
							des = (TextView) findViewById(R.id.des_activity_detail);
							thumbnail = (ImageView) findViewById(R.id.imageActivity);

							// display activity data in textview

							Log.w("image", TAG_THUMBNAILIMAGEURL);

							// activity_id.setText(activity.getString(TAG_ID_ACTIVITY));
							name_activity = activity.getString(TAG_NAME);
							beginDay = activity.getString(TAG_STARTDAY);
							name.setText(activity.getString(TAG_NAME));
							location.setText("Địa điểm : "
									+ activity.getString(TAG_LOCATION));
							time.setText("Thời gian : " + "Từ "
									+ activity.getString(TAG_STARTDAY)
									+ " đến " + activity.getString(TAG_ENDDAY));

							date.setText(activity.getString(TAG_CREATEDATE));
							des.setText(activity.getString(TAG_DESCRIPTION));
							// imageLoader.DisplayImage(activity.getString(TAG_THUMBNAILIMAGEURL),
							// thumbnail);
							imageLoader.DisplayImage(
									url_image+activity.getString(TAG_THUMBNAILIMAGEURL),
									thumbnail);
						} else {
							// not found
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			pDialog.dismiss();
		}
	}

	/**
	 * set button share into actionbar
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.detail_activity_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * On select action bar icon
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// take appropriate action for each item click
		switch (item.getItemId()) {
		case R.id.action_share_place:
			Intent share = new Intent(android.content.Intent.ACTION_SEND);
			share.setType("text/plain");
			share.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			// add data to intent
			share.putExtra(Intent.EXTRA_SUBJECT, "Share to Facebook");
			share.putExtra(Intent.EXTRA_TEXT,
					"http://tinhnguyen.edu.vn/activities/detail/" + id_activity);
			startActivity(Intent.createChooser(share, "Share to Facebook"));
			return true;
		case R.id.action_calendar:
			// ACTION_INSERT does not work on all phones
			// use  Intent.ACTION_EDIT in this case
			/*Intent intent = new Intent(Intent.ACTION_INSERT);
			intent.setData(CalendarContract.Events.CONTENT_URI);
			*/
			Calendar beginday = Calendar.getInstance();
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
			Date d;
			long milliseconds = 0;
			try {
				d = f.parse(beginDay);
				milliseconds = d.getTime();
				 Toast.makeText(getApplicationContext(), String.valueOf(d), Toast.LENGTH_SHORT).show();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			
	        Intent intent = new Intent(Intent.ACTION_EDIT);
	        intent.setType("vnd.android.cursor.item/event");
	        //Toast.makeText(getApplicationContext(), String.valueOf(milliseconds), Toast.LENGTH_SHORT).show();
			intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, milliseconds);
	        //intent.putExtra("allDay", true);
	        //intent.putExtra("rrule", "FREQ=YEARLY");
	        intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, milliseconds);
	        intent.putExtra("title", name_activity);
	        intent.putExtra("description", "This is a sample description");
	        startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
